# -*- coding: utf-8 -*-
import re
import requests
import subprocess


# ##########################################
# 主程序开始
# ##########################################
# 定义查询的日期
# 定义更新的报关单数量
# 使用cookie
# 登录信息
index_url= 'http://www.npedi.com/edi/ediweb/index.jsp'
# <img border=0 src="/edi/ediweb/image.jsp">
# <img id="img" border=0 src="/edi/ediweb/jcaptcha.jpg" onclick="refresh();" alt="点击更换验证码"/>
pic1_pattern = 'src="/edi/ediweb/image.jsp"'
pic2_pattern = 'src="/edi/ediweb/jcaptcha.jpg"'
pic_url1 = 'http://www.npedi.com/edi/ediweb/image.jsp'
pic_url2 = 'http://www.npedi.com/edi/ediweb/jcaptcha.jpg'
pic_url = ''


login_url = 'http://www.npedi.com/edi/webLoginAction.do'
auth_url = 'http://127.0.0.1:50003/auth_npedi'
# index_url='http://www.npedi.com/edi/ediweb/index.jsp'
post_data = dict()
post_data['usercode'] = 'GUEST'
post_data['password'] = 'guest'
post_data['randcode'] = ''
post_data['x'] = '0'
post_data['y'] = '0'
login_pattern = '<font color="#FF3300" >GUEST</font>'
cookies = ''
code = ''
# 登录的地址

def CheckPicType():
    global pic_url
    index_html = requests.get(index_url).text
    if re.search(pic1_pattern, index_html):
        pic_url = pic_url1
    if re.search(pic2_pattern, index_html):
        pic_url = pic_url2
    print pic_url

def randcode(pic):
    with open('code.jpg', 'wb') as f1:
        f1.write(pic)
    subprocess.call('tesseract.exe code.jpg code digits')
    with open('code.txt') as f2:
        t = f2.read()
    print 'txt:', t
    t = re.findall('\d', t)
    if len(t) == 4:
        return ''.join(t)
    else:
        return ''

def getpic(url):
    global cookies, code
    r = requests.get(url)
    code = randcode(r.content)
    cookies = r.cookies


def gethtml(url, params):
    # post_data['randcode']=''
    login_html = requests.get(url, params=params, cookies=cookies).text
    return login_html


def checkhtml(url, params):
    h = gethtml(url, params)
    if re.search(login_pattern, h):
        print 'success'
        return True
    else:
        print 'login fail'
        return False


def savecookie(url, cookie):
    data = {'cookie': cookie, 'site': 'npedi', 'action': 'remote'}
    headers = {'Accept': 'application/json'}
    r = requests.post(url, data=data, headers=headers)
    print r.text


def refresh(url):
    params = {'site': 'npedi', 'action': 'remote'}
    headers = {'Accept': 'application/json'}
    auth = requests.get(auth_url, params=params, headers=headers).json()
    return requests.get(url, cookies=dict(JSESSIONID=auth['cookie'])).text if auth['result'] else ''

html = refresh(login_url)
if re.search(login_pattern, html):
    print 'session alive'
else:
    print 'session expired'
    while not checkhtml(login_url, post_data):
        CheckPicType()
        getpic(pic_url)
        post_data['randcode'] = code
        print post_data['randcode'], cookies
    savecookie(auth_url, cookies['JSESSIONID'])
